﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Cache;
using Wicture.QPZS.EPC.API.Domain;
using Wicture.QPZS.EPC.API.Domain.Entities;

namespace Wicture.QPZS.EPC.API.Throttlings
{
    public class ApiFrequencyThrotting : FrequencyThrotting
    {
        public override decimal Order => 7;

        protected override bool NeedFrequency(ThrottlingContext context)
        {
            var frequency = context.AccountPackageApi?.Frequency ?? 0;
            return frequency > 0;
        }

        protected override void SetFrequency(ThrottlingContext context, InvocationFrequency invocationFrequency)
        {
            var frequency = context.AccountPackageApi?.Frequency;
            var counter = invocationFrequency.ApiCounters.FirstOrDefault(a => a.Name == context.ApiName);
            if (counter == null)
            {
                counter = new ApiCounter { Name = context.ApiName };
                invocationFrequency.ApiCounters.Add(counter);
            }
            if (counter?.Count > frequency)
            {
                LoggerManager.Logger.LogWarning($"{context.AccountName}: 调用频率超出: {invocationFrequency.Total} / {frequency}.");
                throw new LogicalException($"{context.ApiName}接口调用太频繁，超出每分钟{frequency}次。", 603);
            }
            counter.Count += 1;
        }
    }
}
